import React, { useState, useEffect } from 'react';
import { Input, Tabs, message, Select } from 'antd';
import services from 'src/services/api';
import TableEditor from 'src/components/TableEditor';
import CustomForm from 'src/components/CustomForm';
import { useRef } from 'react';

const { TabPane } = Tabs;
export default function(props) {
  const [dataTypeLists, useDataTypeLists] = useState([]);
  const [modelInput, setModelInput] = useState([]);
  const [modelOutput, setModelOutput] = useState([]);

  const form = useRef(null);
  useEffect(() => {
    // detail();
    getDatatype();
  }, []);

  function getDatatype() {
    services.dataType.list({}).then((res) => {
      if (res.code === 0) {
        useDataTypeLists(res.data);
      }
    });
  }

  function handleChangeCodeInput(value, record, index) {
    modelInput[index] = { ...record, name: value };
    setModelInput(Object.assign([], modelInput));
  }

  function handleChangeTypeInput(value, record, index) {
    modelInput[index] = { ...record, data_type: value };
    setModelInput(Object.assign([], modelInput));
  }

  function handleChangeCodeOutput(value, record, index) {
    modelOutput[index] = { ...record, name: value };
    setModelOutput(Object.assign([], modelOutput));
  }

  function handleChangeTypeOutput(value, record, index) {
    modelOutput[index] = { ...record, data_type: value };
    setModelOutput(Object.assign([], modelOutput));
  }

  function changeHandleTablesInput(datas) {
    setModelInput(datas);
  }

  function changeHandleTablesOutput(datas) {
    setModelOutput(datas);
  }

  function handleSubmit() {
    form.current.validateFields((err, values) => {
      if (!err) {
        const params = {
          ...values,
        };

        try {
          validate(modelInput, '输入参数');
          validate(modelOutput, '输出参数');
          params.model_input = modelInput;
          params.model_output = modelOutput;
          services.model.addByCite(params).then((data) => {
            if (data.code === 0) {
              message.success(data.msg);
              if (props.closeModal) {
                props.closeModal();
              }
            } else {
              message.error(data.msg);
            }
          });
        } catch (err) {
          message.warning(err);
        }
      }
    });
  }

  function validate(data, title) {
    if (data.length === 0) {
      throw '请输入' + title;
    }
    const isRepeat = checkRepeat(data.map((it) => it.name));
    if (isRepeat) {
      throw title + '有重复字段名';
    }
    data.forEach((it) => {
      if (it.name === '') {
        throw '请输入' + title + '字段名';
      }
      if (!it.data_type) {
        throw '请选择' + title + '字段类型';
      }
    });
  }

  // 检查数组是否重复，如果重复，则返回true,否则false
  function checkRepeat(data) {
    const length = data.length;
    const removeRepeatLength = [...new Set(data)].length;
    if (length === removeRepeatLength) {
      return false;
    } else {
      return true;
    }
  }

  const columnsTestIn = [
    {
      title: '字段名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record, index) => {
        return <Input value={text} onChange={(e) => handleChangeCodeInput(e.target.value, record, index)} />;
      },
    },
    {
      title: '类型',
      dataIndex: 'data_type',
      key: 'data_type',
      render: (text, record, index) => {
        return (
          <Select
            style={{ width: '150px' }}
            value={text}
            onChange={(value) => handleChangeTypeInput(value, record, index)}
          >
            {dataTypeLists.map((it) => (
              <Select.Option value={it.code}>{it.name}</Select.Option>
            ))}
          </Select>
        );
      },
    },
  ];
  const columnsTestOut = [
    {
      title: '字段名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record, index) => {
        return <Input value={text} onChange={(e) => handleChangeCodeOutput(e.target.value, record, index)} />;
      },
    },
    {
      title: '类型',
      dataIndex: 'data_type',
      key: 'data_type',
      render: (text, record, index) => {
        return (
          <Select
            style={{ width: '150px' }}
            value={text}
            onChange={(value) => handleChangeTypeOutput(value, record, index)}
          >
            {dataTypeLists.map((it) => (
              <Select.Option value={it.code}>{it.name}</Select.Option>
            ))}
          </Select>
        );
      },
    },
  ];

  const formItems = [
    {
      label: {
        label: '模型名称',
        className: 'tantuer-form-item2 tantuer-form-item-nowrap',
      },
      name: 'model_name',
      options: {
        initialValue: '',
        rules: [
          { required: true, message: '请填写模型名称' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' }
        ],
      },
      component: <Input placeholder='请填写' />,
    },
    {
      label: {
        label: 'URL',
        className: 'tantuer-form-item2 tantuer-form-item-nowrap',
      },
      name: 'model_url',
      options: {
        initialValue: '',
        rules: [
          { required: true, message: '请填写URL' },
          {
            pattern: /^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(?::\d{1,5})?/i,
            message: '请输入正确的URL',
          },
        ],
      },

      component: <Input />,
    },
  ];
  return (
    <div className='tantuer'>
      <CustomForm
        colNum={2}
        closeModal={props.closeModal}
        createForm={(ref) => (form.current = ref)}
        formItems={formItems}
        onHandleSubmit={handleSubmit}
      >
        <Tabs defaultActiveKey='1' style={{ marginBottom: '20px' }}>
          <TabPane tab='输入参数' key='1'>
            <TableEditor
              columns={columnsTestIn}
              initItem={{ name: '', data_type: '' }}
              dataSource={modelInput}
              onChange={changeHandleTablesInput}
            />
          </TabPane>
          <TabPane tab='输出参数' key='2'>
            <TableEditor
              columns={columnsTestOut}
              initItem={{ name: '', data_type: '' }}
              dataSource={modelOutput}
              onChange={changeHandleTablesOutput}
            />
          </TabPane>
        </Tabs>
      </CustomForm>
    </div>
  );
}
